<template>
  <!-- 按条件渲染另外动态添加表格并计算 -->
  <div id="TableMathMove">
    <el-form
      ref="ruleFormRef"
      :model="createOrderForm"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      :rules="rules"
    >
      <div class="title"><div class="com">按条件渲染:各个列表是循环出来的</div></div>
      <!-- 隔离-- -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="多选" prop="typeOfService">
            <el-checkbox-group v-model="createOrderForm.typeOfService">
              <el-checkbox v-for="item in cities" :label="item" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 隔离-- -->
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="步骤一 🤖" prop="typeOfContainerGoods">
            <el-radio-group v-model.trim="createOrderForm.typeOfContainerGoods">
              <el-radio v-for="item in selectItem?.typeOfContainerGoods" :label="item.name" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="步骤二 🤖" prop="businessType">
            <el-radio-group v-model.trim="createOrderForm.businessType">
              <el-radio v-for="item in selectItem?.businessType.slice(1, 3)" :label="item.name" />
              <el-radio
                :label="selectItem?.businessType[0].name"
                v-if="createOrderForm.typeOfContainerGoods === '点击第一步'"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="步骤三 🤖" prop="orderType">
            <el-radio-group v-model.trim="createOrderForm.orderType">
              <el-radio v-for="item in selectItem?.ordertype.slice(0, 2)" :label="item.name" />
              <el-radio
                :label="selectItem?.ordertype[2].name"
                v-if="
                  createOrderForm.typeOfContainerGoods === '点击第一步' && createOrderForm.businessType === '点击第二步'
                "
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 隔离-- -->
      <el-row
        :gutter="24"
        v-if="
          createOrderForm.typeOfContainerGoods === '点击第一步' &&
          createOrderForm.businessType === '点击第二步' &&
          createOrderForm.orderType === '点击第三步'
        "
      >
        <el-col :span="8">
          <el-form-item label="彩蛋一 🥳" label-width="300">
            <el-input v-model.trim="createOrderForm.amazonId" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="彩蛋二 🥳" label-width="300">
            <el-input v-model.trim="createOrderForm.referenceId" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="彩蛋三 🥳" label-width="300">
            <el-input v-model.trim="createOrderForm.fbaShipmentId" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 隔离-- -->
      <div class="title"><div class="com">表单一:自动计算</div></div>
      <div class="huoPinXiangQing">
        <div class="tableList">
          <el-table :data="createOrderForm.detailsOfGoodsList" border style="width: 100%" stripe height="100%">
            <el-table-column label="序号" fixed="left" width="60" type="index" />
            <el-table-column label="数字 1" width="180">
              <template #default="{ row, $index }">
                <el-form-item
                  style="margin: 16px 0 !important"
                  :rules="rules.specificationOfPacking"
                  :prop="'detailsOfGoodsList.' + $index + '.specificationOfPacking'"
                >
                  <el-input min="0" v-model.number="row.specificationOfPacking" @change="gieceNumberData"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column prop="unitPrice" label="字符 5">
              <template #default="{ row, $index }">
                <el-form-item v-model.trim="row.unitPrice" style="margin: 16px 0 !important">
                  <el-input v-model.trim="row.unitPrice"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="字符 6">
              <template #default="{ row }">
                <el-form-item style="margin: 16px 0 !important">
                  <el-input v-model.trim="row.totalPrice"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- ------------- -->
            <el-table-column label="数字 7">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'detailsOfGoodsList.' + $index + '.grossWeight'"
                  :rules="rules.grossWeight"
                  style="margin: 16px 0 !important"
                >
                  <el-input id="inputA" min="0" v-model.number="row.grossWeight" @change="grossWeightData"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数字 8" prop="volume">
              <template #default="{ row, $index }">
                <el-form-item
                  style="margin: 16px 0 !important"
                  :prop="'detailsOfGoodsList.' + $index + '.volume'"
                  :rules="rules.volume"
                >
                  <el-input min="0" v-model.number="row.volume" @change="volumeData"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数字 9" prop="packingSize">
              <template #default="{ row, $index }">
                <el-form-item
                  style="margin: 16px 0 !important"
                  :prop="'detailsOfGoodsList.' + $index + '.packingSize'"
                  :rules="rules.packingSize"
                >
                  <el-input min="0" v-model.number="row.packingSize" @change="packingSizeData"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- ----------------- -->
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleClick">增加</el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.passive="removeFruitConfig(row)"
                  v-if="createOrderForm.detailsOfGoodsList.length > 1"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="zong">
          <div class="zongji" style="margin-right: 20px; width: 100px">计算一下</div>
          <div class="input_zongji">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="件数:">
                  <el-input v-model.trim="createOrderForm.numberOfPieces" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="毛重:">
                  <el-input v-model.trim="createOrderForm.grossWeights" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="体积:">
                  <el-input v-model.trim="createOrderForm.volumes" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="包装尺寸:">
                  <el-input v-model.trim="createOrderForm.packingSizes" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>

      <!-- 隔离-- -->
      <div class="title"><div class="com">表单二:样式改变</div></div>
      <el-button plain class="gongNengBtn" @click="dealAdd">新增</el-button>
      <div class="table">
        <el-table :data="createOrderForm.receivab" style="width: 100%" border>
          <el-table-column label="序号" fixed="left" :index="indexMethod" type="index" width="60" />
          <el-table-column prop="master" label="不变一" />
          <el-table-column prop="points" label="不变二" />
          <el-table-column prop="nameOfFee" label="可变三" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-select v-model="row.nameOfFee" class="m-2" placeholder="请输入内容">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="可变四" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-input v-model.trim="row.amount" placeholder="请输入内容"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="可变五" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-select v-model="row.currency" class="m-2" placeholder="请输入内容">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="exchangeRate" label="不变六" />
          <el-table-column prop="costTime" label="可变七" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-date-picker
                  v-model="row.costTime"
                  type="date"
                  placeholder="请输入内容"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="reciprocalUnit" label="可变八" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-select v-model="row.reciprocalUnit" class="m-2" placeholder="请输入内容">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="localCurrencyAmount" label="不变九" />
          <el-table-column prop="remarks" label="可变十" width="250px">
            <template #default="{ row }">
              <el-form-item style="margin-bottom: 0 !important" class="inputBar">
                <el-input v-model.trim="row.remarks" placeholder="请输入内容"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.stop="removeFruitConfigYf(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider>
        <el-icon><star-filled /></el-icon>
      </el-divider>
      <el-button @click="yuJiaoYan(ruleFormRef)">表单预校验</el-button>
      <el-button @click="reset(ruleFormRef)">重置绑定规则的字段</el-button>
    </el-form>
  </div>
</template>

<script lang="ts" setup name="TableMathMove">
/**
 * @标题 : 动态表格计算结果
 * */
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { selectItem } from '@/data/tableData/tableData'
import type { GoodsList } from '@/data/tableData/tableType'
// 验证
import { customerNumberValidator } from '@/hooks/useVerification'
// 标记-- 表单
const formSize = ref('default')
// 服务类型
const cities = ref(['option1', 'option2', 'option3', 'option4', 'option5', 'option6', 'option7', 'option8'])

const createOrderForm = ref({
  typeOfContainerGoods: '',
  // 业务类型
  businessType: '',
  // 订单类型
  orderType: '',
  // 服务类型
  typeOfService: [],
  // Amazon(亚马逊卖家/店铺)ID
  amazonId: '',
  // Roference ID(亚马边内部编号)
  referenceId: '',
  // FBA SHIPMENT ID(货件编号)
  fbaShipmentId: '',
  // 件数
  numberOfPieces: 0,
  // 毛重
  grossWeights: 0,
  // 体积
  volumes: 0,
  // 包装尺寸
  packingSizes: 0,
  // 表格一
  detailsOfGoodsList: [
    {
      // 件数/包装
      specificationOfPacking: '',
      // 货物品名（中英文)HS编码
      nameOfGoods: '',
      // 材质/用途
      material: '',
      // 数量(PCS)
      quantity: '',
      // 单价(USD)
      unitPrice: '',
      // 总价(USD)
      totalPrice: '',
      // 毛重
      grossWeight: '',
      // 体积
      volume: '',
      // 包装尺寸
      packingSize: ''
    }
  ],
  // 表格二
  receivab: [
    {
      // MBL NO
      master: '',
      // HBL NO
      points: '',
      // 费用名称
      nameOfFee: '',
      // 金额
      amount: '',
      // 币种
      currency: '',
      // 汇率
      exchangeRate: '',
      // 费用时间
      costTime: '',
      // 往来单位
      reciprocalUnit: '',
      // 本币金额
      localCurrencyAmount: '',
      // 备注
      remarks: ''
    }
  ]
})

// 隔离--计算总价-------------------------------------------------------
const gieceNumberData = () => {
  jisuan('jianshu', createOrderForm.value)
  console.log('🌈成功->信息', createOrderForm.value.detailsOfGoodsList[0].specificationOfPacking)
  console.log(`asd`)
}

// 毛重-------------------------------------------------------
const grossWeightData = () => {
  jisuan('maozhong', createOrderForm.value)
  console.log(`123`)
}
// 体积-------------------------------------------------------
const volumeData = () => {
  jisuan('tiji', createOrderForm.value)
  console.log(`456`)
}
// 包裝尺寸-------------------------------------------------------
const packingSizeData = () => {
  jisuan('chicun', createOrderForm.value)
  console.log(`qwe`)
}
// 点击新增行-------------------------------------------------------
const handleClick = () => {
  createOrderForm.value.detailsOfGoodsList.push({
    // 件数/包装
    specificationOfPacking: '',
    // 货物品名（中英文)HS编码
    nameOfGoods: '',
    // 材质/用途
    material: '',
    // 数量(PCS)
    quantity: '',
    // 单价(USD)
    unitPrice: '',
    // 总价(USD)
    totalPrice: '',
    // 毛重
    grossWeight: '',
    // 体积
    volume: '',
    // 包装尺寸
    packingSize: ''
  })
}

// 删除1-------------------------------------------------------
const removeFruitConfig = (row: GoodsList) => {
  const index = createOrderForm.value.detailsOfGoodsList.indexOf(row as GoodsList)
  if (index !== -1) {
    createOrderForm.value.detailsOfGoodsList.splice(index, 1)
  }
  jisuan('jianshu', createOrderForm.value)
  jisuan('maozhong', createOrderForm.value)
  jisuan('tiji', createOrderForm.value)
  jisuan('chicun', createOrderForm.value)
}

// 计算总价的函数-------------------------------------------------------
const jisuan = (canShu: string, createOrderForm: any) => {
  // 计算尺寸的函数
  const jieguo = (val: number[]) => {
    let total = 0
    val.map((sub: number) => {
      return (total = total + +sub)
    })
    if (['jianshu'].includes(canShu)) {
      return (createOrderForm.numberOfPieces = total)
    } else if (['maozhong'].includes(canShu)) {
      return (createOrderForm.grossWeights = total)
    } else if (['tiji'].includes(canShu)) {
      return (createOrderForm.volumes = total)
    } else if (['chicun'].includes(canShu)) {
      return (createOrderForm.packingSizes = total)
    }
  }
  // 标记-- 计算件数
  if (['jianshu'].includes(canShu)) {
    return jieguo(createOrderForm.detailsOfGoodsList.map((item: GoodsList) => item.specificationOfPacking))
  } else if (['maozhong'].includes(canShu)) {
    return jieguo(createOrderForm.detailsOfGoodsList.map((item: GoodsList) => item.grossWeight))
  } else if (['tiji'].includes(canShu)) {
    return jieguo(createOrderForm.detailsOfGoodsList.map((item: GoodsList) => item.volume))
  } else if (['chicun'].includes(canShu)) {
    return jieguo(createOrderForm.detailsOfGoodsList.map((item: GoodsList) => item.packingSize))
  }
}

// 隔离--  表单预校验ref-------------------------------------------------------
const ruleFormRef = ref()
//  表单预校验-------------------------------------------------------
const yuJiaoYan = (formEl: FormInstance | undefined) => {
  console.log('🚚...  保存', createOrderForm.value)
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      ElMessage.success({ message: `保存并提交审核成功` })
      ruleFormRef.value?.clearValidate()
    } else {
      console.log('失败')
      return false
    }
  })
}

//   重置-------------------------------------------------------
const reset = (formEl: FormInstance | undefined) => {
  ruleFormRef.value?.resetFields()
}

// 隔离--  新增表单二-------------------------------------------------------
const dealAdd = () => {
  createOrderForm.value.receivab.push({
    // MBL NO
    master: '1',
    // HBL NO
    points: '2',
    // 费用名称
    nameOfFee: '',
    // 金额
    amount: '',
    // 币种
    currency: '',
    // 汇率
    exchangeRate: '',
    // 费用时间
    costTime: '',
    // 往来单位
    reciprocalUnit: '',
    // 本币金额
    localCurrencyAmount: '',
    // 备注
    remarks: ''
  })
}
// 删除
const removeFruitConfigYf = (row: any) => {
  const index = createOrderForm.value.receivab.indexOf(row as any)
  if (index !== -1) {
    createOrderForm.value.receivab.splice(index, 1)
  }
}
const options = [
  {
    value: 'RMB',
    label: 'RMB'
  },
  {
    value: 'RMB',
    label: 'RMB'
  },
  {
    value: 'RMB',
    label: 'RMB'
  },
  {
    value: 'RMB',
    label: 'RMB'
  },
  {
    value: 'RMB',
    label: 'RMB'
  }
]
// 自定义序号
const indexMethod = (index: number) => {
  return index + 1 * 1
}
// 规则
const rules = ref<FormRules>({
  // 多选
  typeOfService: [
    {
      required: true,
      message: '多选必填项',
      trigger: ['blur', 'change']
    }
  ],
  // 步骤一
  typeOfContainerGoods: [
    {
      required: true,
      message: '步骤一必填项',
      trigger: ['blur', 'change']
    },
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    }
  ],
  // 步骤二
  businessType: [
    {
      required: true,
      message: '步骤二必填项',
      trigger: ['blur', 'change']
    },
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    }
  ],
  // 步骤三
  orderType: [
    {
      required: true,
      message: '步骤三必填项',
      trigger: ['blur', 'change']
    },
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    }
  ],

  // 数字1
  specificationOfPacking: [
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    },
    {
      required: true,
      message: '数字1必填项',
      trigger: ['blur', 'change']
    }
  ],
  // 数字7
  grossWeight: [
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    },
    {
      required: true,
      message: '数字7必填项',
      trigger: ['blur', 'change']
    }
  ],
  //数字8
  volume: [
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    },
    {
      required: true,
      message: '数字8必填项',
      trigger: ['blur', 'change']
    }
  ],
  // 数字9
  packingSize: [
    {
      validator: customerNumberValidator,
      trigger: ['blur', 'change'],
      max: 50,
      min: 5
    },
    {
      required: true,
      message: '数字9必填项',
      trigger: ['blur', 'change']
    }
  ]
})
</script>

<style lang="scss" scoped>
#TableMathMove {
  .title {
    margin-bottom: 10px;
    height: 50px;
    line-height: 50px;
    font-weight: 900;
    border-bottom: 1px solid #eee;
    border-top: 1px solid #eee;
    .com {
      margin-left: 20px;
    }
  }

  .zong {
    margin: 30px 0;
    display: flex;
    align-items: center;
    .zongji {
      margin-left: 20px;
      width: 40px;
      color: red;
    }
  }
  .jiBenXinXi,
  .yunShuXinXi,
  .RenYuanXinXi,
  .CaiWuXinXi {
    margin: 30px 0;
  }

  .huoPinXiangQing {
    ::v-deep(.el-form-item__content) {
      margin-left: 0px !important;
    }
    ::v-deep(.el-form-item--default) {
      margin-top: 10px !important;
      margin-bottom: 10px !important;
    }
    .tableList {
      padding: 0 20px;
      margin: 0 auto;
    }
  }
  ::v-deep(.el-input__wrapper) {
    width: 221px !important;
    // flex: 1 !important;
  }
  .huoPinXiangQing {
    :v-deep(.el-form-item--default) {
      margin: 16px 0 !important;
    }
  }

  // 动态表格二
  .gongNengBtn {
    margin-bottom: 20px;
  }
  ::v-deep(.el-table__row) {
    &:hover {
      > td {
        background: #fff !important;
      }
    }
  }
  .inputBar {
    ::v-deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0px transparent !important;
      &.is-focus {
        box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset !important;
      }
      &:hover {
        box-shadow: 0 0 0 1px #dcdfe6 inset !important;
      }
    }
  }
}
</style>
